import Vue from 'vue'
import store from './store'
import App from './App'

import * as filters from './filters'
import * as config from './config'
// import {util} from './util/util.js'

Object.keys(filters).forEach(key => {
	Vue.filter(key, filters[key])
})

const defConfig = config.def

const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

let userInfo = undefined
let token = undefined

const logout = () => {
	userInfo = undefined
	uni.removeStorage({
		key: 'userInfo'
	})
}

const setUserInfo = (i) => {
	userInfo = i
}

const isVip = () => {
	return userInfo && userInfo.level
}

let loginLock = false

const request = (_gp, _mt, data = {}, failCallback) => {
	//异步请求数据
	return new Promise(resolve => {
		token = uni.getStorageSync('token')
		let baseUrl = config.def().baseUrl
		uni.request({
			url: baseUrl /* + '/api' */+_gp+_mt,
			data: {
				...data,
				/* _gp,
				_mt */
			},
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'token': token
			},
			success: (res) => {
				if (res.statusCode===200) {
					if (res.data.code === 0) {
						resolve(res.data);
					} else if (res.data.errno === 10001) {
						if (failCallback) {
							failCallback(res.data)
						}
						if (!loginLock) {
							loginLock = true
							uni.showModal({
								title: '登录提示',
								content: '您尚未登录，是否立即登录？',
								showCancel: true,
								confirmText: '登录',
								success: (e) => {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}
								},
								fail: () => {},
								complete: () => {
									loginLock = false
								}
							})
						}

					} else {
						if (failCallback) {
							failCallback(res.data)
						} else {
							uni.showToast({
								title: res.data.errmsg,
								icon: 'none'
							})
						}
					}
				}
			}
		})
	})
}
const request1 = (_gp, _mt, data = {}, failCallback) => {
	//异步请求数据
	return new Promise(resolve => {
		token = uni.getStorageSync('token')
		let baseUrl = config.def().baseUrl
		uni.request({
			url: baseUrl /* + '/api' */+_gp+_mt,
			data: {
				...data,
				/* _gp,
				_mt */
			},
			method: 'GET',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'token': token
			},
			success: (res) => {
				if (res.statusCode===200) {
					if (res.data.code === 0) {
						resolve(res.data);
					} else if (res.data.errno === 10001) {
						if (failCallback) {
							failCallback(res.data)
						}
						if (!loginLock) {
							loginLock = true
							uni.showModal({
								title: '登录提示',
								content: '您尚未登录，是否立即登录？',
								showCancel: true,
								confirmText: '登录',
								success: (e) => {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}
								},
								fail: () => {},
								complete: () => {
									loginLock = false
								}
							})
						}

					} else {
						if (failCallback) {
							failCallback(res.data)
						} else {
							uni.showToast({
								title: res.data.errmsg,
								icon: 'none'
							})
						}
					}
				}
			}
		})
	})
}


const uploadImg = (successCallback) => {
	uni.chooseImage({
		sizeType: ['compressed'],
		success: function(res) {
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				uni.uploadFile({
					url: 'https://zlzfcloud.xyz/api/web/upload',
					filePath: res.tempFilePaths[i],
					name: 'file',
					success: function(uploadRes) {
						uni.hideLoading()
						if (uploadRes.statusCode === 200) {
							if (successCallback) {
								successCallback("https://zlzfcloud.xyz" + JSON.parse(uploadRes.data).msg)
							} else {
								uni.showToast({
									title: '上传成功',
									icon: 'none'
								})
							}
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '网络错误 code=' + uploadRes.statusCode,
								icon: 'none'
							})
						}
					}
				})
			}
		}
	})
}

function get_suffix(filename) {
	var pos = filename.lastIndexOf('.')
	var suffix = ''
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}

function random_string(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const toLogin = () => {
	uni.login({
		provider: 'weixin',
		success: (wxres => {
			console.log("wxres",wxres)
			request('/api/web/wxlogin','',{
				code: wxres.code
			}, failres => {
				uni.showToast({
					title: failres.msg,
					icon: "none"
				});
			}).then(res => {
				uni.setStorageSync('token', res.data.token);
				uni.setStorageSync('userId', res.data.user.userId);
			})
		})
	})
}

const getUserInfo = () =>{
	uni.getUserProfile({
		desc:'Wexin',     // 这个参数是必须的
		success:res=>{
		   console.log("userRes",res)
		   uni.setStorageSync('nickName', res.userInfo.nickName);
		   uni.setStorageSync('avatarUrl', res.userInfo.avatarUrl);
		   uni.login({
				provider: 'weixin',
				success: (wxres => {
					console.log("wxres",wxres)
					request('/api/web/wxlogin','',{
						code: wxres.code,
					}, failres => {
						uni.showToast({
							title: failres.msg,
							icon: "none"
						});
					}).then(res1 => {
						console.log("res1",res1)
						uni.setStorageSync('token', res1.data.token);
						uni.setStorageSync('userId', res1.data.user.userId);
						console.log(uni.getStorageSync("nickName"))
						console.log(uni.getStorageSync("avatarUrl"))
						console.log(uni.getStorageSync("token"))
						console.log(uni.getStorageSync("userId"))
					})
				})
			})
	   },
	   fail:err=>{
		   
	   }
	})
}

Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$api = {
	msg,
	prePage,
	request,
	request1,
	uploadImg,
	logout,
	isVip,
	setUserInfo,
	defConfig,
};
Vue.prototype.$util = {
	toLogin,
	getUserInfo
}
//#ifdef H5
// Vue.prototype.$jweixin = jweixin;
//#endif

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()
